package com.zzzy.doc.controller;

import com.zhuozhengsoft.pageoffice.FileSaver;
import com.zhuozhengsoft.pageoffice.OpenModeType;
import com.zhuozhengsoft.pageoffice.PageOfficeCtrl;
import com.zhuozhengsoft.pageoffice.word.DataRegionReader;
import com.zhuozhengsoft.pageoffice.word.WordDocumentReader;
import com.zhuozhengsoft.pageoffice.word.WordDocumentWriter;
import com.zzzy.common.util.FileUtil;
import com.zzzy.common.vo.AjaxResult;
import com.zzzy.common.vo.PageResult;
import com.zzzy.doc.dao.entity.DocFileTemplate;
import com.zzzy.doc.service.DocFileTemplateService;
import com.zzzy.doc.vo.template.DocTemplateAddReq;
import com.zzzy.doc.vo.template.DocTemplatePageReq;
import com.zzzy.doc.vo.template.DocTemplateSimpleUpdateReq;
import com.zzzy.doc.vo.template.file.DocFileTemplatePageRes;
import com.zzzy.doc.vo.template.file.OpenDocFileTemplateWordRes;
import com.zzzy.framework.common.enums.common.TemplateStatusEnum;
import com.zzzy.framework.common.util.SecurityUtils;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springdoc.api.annotations.ParameterObject;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import javax.validation.constraints.NotNull;
import java.util.ArrayList;


/**
 * 公文文件模板
 *
 * @author fc
 * @since 2024-08-08
 */
@Tag(name = "公文文件模板", description = "doc000")
@Validated
@RestController
@RequestMapping("/doc/fileTemplate")
public class DocFileTemplateController {

    @Resource
    private DocFileTemplateService docFileTemplateService;

    @GetMapping(value = "/page")
    @Operation(summary = "分页列表")
    @PreAuthorize("@pvs.hasPermission('doc:fileTemplate:page')")
    public AjaxResult<PageResult<DocFileTemplatePageRes>> page(@Valid @ParameterObject DocTemplatePageReq queryReq) {
        PageResult<DocFileTemplatePageRes> docFileTemplatePage = docFileTemplateService.getDocFileTemplateResPage(queryReq);
        return AjaxResult.success(docFileTemplatePage);
    }

    @PostMapping("/add")
    @Operation(summary = "新增模板,返回模板ID")
    @PreAuthorize("@pvs.hasPermission('doc:fileTemplate:add')")
    public AjaxResult<Long> add(@Valid @RequestBody DocTemplateAddReq addReq) {
        return AjaxResult.success(docFileTemplateService.add(addReq));
    }

    @GetMapping("/getBasicInfo/{id}")
    @Operation(summary = "获取模板基本信息")
    @Parameter(name = "id", description = "公文模板ID", required = true)
    @PreAuthorize("@pvs.hasPermission('doc:fileTemplate:page')")
    public AjaxResult<DocFileTemplate> getBasicInfo(@NotNull(message = "公文模板ID不能为空") @PathVariable("id") Long id) {
        DocFileTemplate docFileTemplate = docFileTemplateService.getByIdForQuery(id);
        return AjaxResult.success(docFileTemplate);
    }

    @PutMapping("/updateBasicInfo")
    @Operation(summary = "修改模板基本信息")
    @PreAuthorize("@pvs.hasPermission('doc:fileTemplate:update')")
    public AjaxResult updateBasicInfo(@Valid @RequestBody DocTemplateSimpleUpdateReq updateReq) {
        docFileTemplateService.updateBasicInfoById(updateReq);
        return AjaxResult.success();
    }

    @DeleteMapping("/delete/{id}")
    @Operation(summary = "删除模板")
    @Parameter(name = "id", description = "公文模板ID", required = true)
    @PreAuthorize("@pvs.hasPermission('doc:fileTemplate:delete')")
    public AjaxResult delete(@NotNull(message = "公文模板ID不能为空") @PathVariable("id") Long id) {
        docFileTemplateService.deleteById(id);
        return AjaxResult.success();
    }

    @GetMapping(value = "/getOpenTemplateWordRes/{id}")
    @Operation(summary = "打开模板呈批表文件")
    @Parameter(name = "id", description = "公文模板ID", required = true)
    @PreAuthorize("@pvs.hasPermission('doc:fileTemplate:page')")
    public AjaxResult<OpenDocFileTemplateWordRes> getOpenTemplateWordRes(@NotNull(message = "模板ID不能为空") @PathVariable("id") Long id, HttpServletRequest request) {
        DocFileTemplate docFileTemplate = docFileTemplateService.getByIdForQuery(id);
        //work打开方式
        OpenModeType openModeType;
        //只有新建状态且为创建人才能修改模板,其他人只能查看
        if (TemplateStatusEnum.CREATE.getValue().equals(docFileTemplate.getStatus())
                && SecurityUtils.getLoginUser().getId().equals(docFileTemplate.getUserId())){
            openModeType = OpenModeType.docNormalEdit;
        } else {
            openModeType = OpenModeType.docReadOnly;
        }
        PageOfficeCtrl poCtrl = new PageOfficeCtrl(request);
        //打开Word文档地址
        poCtrl.webOpen("/doc/fileTemplate/getTemplateApprovalWordStream/" + id, openModeType, SecurityUtils.getLoginUser().getNickName());
        OpenDocFileTemplateWordRes openWordRes = new OpenDocFileTemplateWordRes();
        poCtrl.setCaption(docFileTemplate.getName());
        poCtrl.setFileTitle(docFileTemplate.getName());
        poCtrl.setWriter(new WordDocumentWriter());
        openWordRes.setHtml(poCtrl.getHtml());
        openWordRes.setApprovalInitDataRegions(docFileTemplate.getApprovalInitDataRegions());
        openWordRes.setApprovalDataRegions(docFileTemplate.getApprovalDataRegions());
        openWordRes.setSave(docFileTemplateService.getButton(id).isUpdate());
        return AjaxResult.success(openWordRes);
    }

    @GetMapping(value = "/getTemplateApprovalWordStream/{id}")
    @Operation(summary = "获取模板呈批表文件流")
    @Parameter(name = "id", description = "公文模板ID", required = true)
    @PreAuthorize("@pvs.hasPermission('doc:fileTemplate:page')")
    public void getTemplateApprovalWordStream(@NotNull(message = "公文模板ID不能为空") @PathVariable("id") Long id, HttpServletResponse response) {
        DocFileTemplate docFileTemplate = docFileTemplateService.getByIdForQuery(id);
        FileUtil.outputFileStream(response, docFileTemplate.getApprovalFileBlob(), docFileTemplate.getName() + docFileTemplate.getApprovalFileExtName());
    }

    @PostMapping(value = "/updateTemplateApprovalWord/{id}")
    @Operation(summary = "保存模板呈批表文件")
    @Parameter(name = "id", description = "公文模板ID", required = true)
    @PreAuthorize("@pvs.hasPermission('doc:fileTemplate:update')")
    public void updateTemplateApprovalWord(@NotNull(message = "公文模板ID不能为空") @PathVariable("id") Long id, HttpServletRequest request, HttpServletResponse response) {
        FileSaver fs = new FileSaver(request, response);
        byte[] byteArray = FileUtil.toByteArray(fs.getFileStream());
        docFileTemplateService.updateTemplateApprovalWord(id, byteArray, fs.getFileExtName());
        fs.setCustomSaveResult("ok");
        fs.close();
    }

    @PostMapping(value = "/updateTemplateApprovalDataRegion/{id}")
    @Operation(summary = "保存模板呈批表数据区域")
    @Parameter(name = "id", description = "公文模板ID", required = true)
    @PreAuthorize("@pvs.hasPermission('doc:fileTemplate:update')")
    public void updateTemplateApprovalDataRegion(@NotNull(message = "公文模板ID不能为空") @PathVariable("id") Long id, HttpServletRequest request, HttpServletResponse response) {
        WordDocumentReader wordDocumentReader = new WordDocumentReader(request, response);
        ArrayList<DataRegionReader> dataRegions = wordDocumentReader.getDataRegions();
        docFileTemplateService.updateTemplateApprovalDataRegion(id, dataRegions);
        wordDocumentReader.setCustomSaveResult("ok");
        wordDocumentReader.close();
    }

    @GetMapping(value = "/showTemplateMainWord/{id}")
    @Operation(summary = "打开模板正文文件")
    @Parameter(name = "id", description = "公文模板ID", required = true)
    @PreAuthorize("@pvs.hasPermission('doc:fileTemplate:page')")
    public AjaxResult<OpenDocFileTemplateWordRes> showTemplateMainWord(@NotNull(message = "模板ID不能为空") @PathVariable("id") Long id, HttpServletRequest request) {
        DocFileTemplate docFileTemplate = docFileTemplateService.getByIdForQuery(id);
        //work打开方式
        OpenModeType openModeType;
        //只有新建状态且为创建人才能修改模板,其他人只能查看
        if (TemplateStatusEnum.CREATE.getValue().equals(docFileTemplate.getStatus())
                && SecurityUtils.getLoginUser().getId().equals(docFileTemplate.getUserId())){
            openModeType = OpenModeType.docNormalEdit;
        } else {
            openModeType = OpenModeType.docReadOnly;
        }
        PageOfficeCtrl poCtrl = new PageOfficeCtrl(request);
        poCtrl.setCaption(docFileTemplate.getName());
        poCtrl.setFileTitle(docFileTemplate.getName());
        poCtrl.setWriter(new WordDocumentWriter());
        //打开Word文档地址
        poCtrl.webOpen("/doc/fileTemplate/getTemplateMainWordStream/" + id, openModeType, SecurityUtils.getLoginUser().getNickName());
        OpenDocFileTemplateWordRes pageOfficeRes = new OpenDocFileTemplateWordRes();
        pageOfficeRes.setHtml(poCtrl.getHtml());
        pageOfficeRes.setMainInitDataTags(docFileTemplate.getMainInitDataTags());
        DocFileTemplatePageRes.Button button = docFileTemplateService.getButton(id);
        pageOfficeRes.setSave(button.isUpdate());
        return AjaxResult.success(pageOfficeRes);
    }

    @GetMapping(value = "/getTemplateMainWordStream/{id}")
    @Operation(summary = "获取模板正文文件流")
    @Parameter(name = "id", description = "公文模板ID", required = true)
    @PreAuthorize("@pvs.hasPermission('doc:fileTemplate:page')")
    public void getTemplateMainWordStream(@NotNull(message = "公文模板ID不能为空") @PathVariable("id") Long id, HttpServletResponse response) {
        DocFileTemplate docFileTemplate = docFileTemplateService.getByIdForQuery(id);
        FileUtil.outputFileStream(response, docFileTemplate.getMainFileBlob(), docFileTemplate.getName() + docFileTemplate.getMainFileExtName());
    }

    @PostMapping(value = "/updateTemplateMainWord/{id}")
    @Operation(summary = "修改模板正文文件")
    @Parameter(name = "id", description = "公文模板ID", required = true)
    @PreAuthorize("@pvs.hasPermission('doc:fileTemplate:update')")
    public void updateTemplateMainWord(@NotNull(message = "公文模板ID不能为空") @PathVariable("id") Long id, HttpServletRequest request, HttpServletResponse response) {
        FileSaver fs = new FileSaver(request, response);
        byte[] byteArray = FileUtil.toByteArray(fs.getFileStream());
        docFileTemplateService.updateTemplateMainWord(id, byteArray, fs.getFileExtName());
        fs.setCustomSaveResult("ok");
        fs.close();
    }

    @PutMapping("/clone/{id}")
    @Operation(summary = "克隆模板,返回模板ID")
    @Parameter(name = "id", description = "公文模板ID", required = true)
    @PreAuthorize("@pvs.hasPermission('doc:fileTemplate:add')")
    public AjaxResult<Long> clone(@NotNull(message = "公文模板ID不能为空") @PathVariable("id") Long id) {
        return AjaxResult.success(docFileTemplateService.cloneById(id));
    }

    @PutMapping("/enable/{id}")
    @Operation(summary = "启用模板")
    @Parameter(name = "id", description = "公文模板ID", required = true)
    @PreAuthorize("@pvs.hasPermission('doc:fileTemplate:add')")
    public AjaxResult enable(@NotNull(message = "公文模板ID不能为空") @PathVariable("id") Long id) {
        docFileTemplateService.enable(id);
        return AjaxResult.success();
    }

    @PutMapping("/disable/{id}")
    @Operation(summary = "停用模板")
    @Parameter(name = "id", description = "公文模板ID", required = true)
    @PreAuthorize("@pvs.hasPermission('doc:fileTemplate:add')")
    public AjaxResult disable(@NotNull(message = "公文模板ID不能为空") @PathVariable("id") Long id) {
        docFileTemplateService.disable(id);
        return AjaxResult.success();
    }
}
